<template>
  <el-card class="userPageBox" v-if="$auth.checkMenuPermissions('system:user:search')">
    <el-row>
      <el-col :span="4">
        <div class="leftDataBox">
          <el-input size="small" placeholder="请输入企业名称" suffix-icon="el-icon-search" class="companySearch"
            v-model="companySearch" @keyup.native.enter="searchCompany" />
          <el-tree :data="companyTree" :props="defaultProps" node-key="companyId" ref="companyTree"
            :default-expanded-keys="defaultExpandedTree" highlight-current @node-click="clickTreeNode"
            :expand-on-click-node="false"></el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="rightDataBox">
          <!--搜索组件-->
          <user-search :user-search="userSearchForm" @onSearch="onSearch" />
          <!--按钮组件-->
          <user-option-btn @add="addBtn" @del="delBtn" @exp="expBtn" />
          <!-- 分隔符 -->
          <hr />
          <!-- 数据展示 -->
          <user-data-table :form-definition="userDataPageForm" :data="userData" @update="updateBtn" @delete="oneDeleteBtn"
            @optionRowIds="optionRowIds" />
          <!-- 数据分页 -->
          <page :total="userDataTotal" @pageSizeChange="pageSizeChange" @currentPageChange="currentPageChange" />
          <!--对话框组件-->
          <common-dialog ref="dialog" :width="680" :executeConfirm="dialogConfirm"
            :child-ref="isOpenInsert === 'insert' ? 'userAddRef' : 'userUpdateRef'">
            <template v-slot:content>
              <user-add v-if="isOpenInsert === 'insert'" ref="userAddRef" :userAdd="userAddEntity"
                :rules="userAddEntityRles" :companyTree="activeDialogCompanyTree" :roleList="activeDialogCompanyRoles" />
              <user-update v-else ref="userUpdateRef" :userUpdate="userUpdateEntity" :rules="userUpdateEntityRles"
                :companyTree="activeDialogCompanyTree" :roleList="activeDialogCompanyRoles" />
            </template>
          </common-dialog>
        </div>
      </el-col>
    </el-row>

  </el-card>
</template>

<script>
import userSearch from "./userSearch.vue";
import userOptionBtn from "./userOptionBtn.vue";
import userDataTable from "./userData.vue";
import page from "@/components/common/page.vue";
import { userSearchForm } from "./entity/userSerch";
import { userDataPageForm } from './entity/userDataForm'
import { getUserPage, userAddApi, userDetailsApi, userUpdateApi, userDeleteApi } from '@/api/system/userApi'
import { getCompanyTree } from '@/api/system/companyApi'
import { getRoleList } from '@/api/system/roleApi'
import commonDialog from "@/components/common/commonDialog.vue";
import userAdd from "./userAdd.vue";
import userUpdate from "./userUpdate.vue";
import { userAddEntity, userUpdateEntity } from './entity/userEntity';
import { userAddEntityRles, userUpdateEntityRles } from './entity/userVerify';
import { noSelectText } from '@/utils/styleUtils'
export default {
  components: { userSearch, userOptionBtn, userDataTable, page, commonDialog, userAdd, userUpdate },
  data() {
    return {
      defaultProps: {
        children: 'child',
        label: 'companyName'
      },
      companySearch: "",//企业按钮搜索
      userSearchForm,//搜索表单
      userDataPageForm,//数据页的数据格式
      userData: [],//数据页数据
      userDataTotal: 0,//数据分页总条数
      companyTree: [],//部门树的数据
      defaultExpandedTree: [],//对话框默认打开部门树
      isOpenInsert: "insert",//对话框展示新增还是修改表单
      activeDialogCompanyTree: [],//激活对话框中的部门树
      activeDialogCompanyRoles: [],//激活对话框中的角色列表
      activeDialogDefaultRoles: [],//激活对话框选中的角色
      userAddEntity,//新增用户对象
      userAddEntityRles,//新增用户对象校验规则
      userUpdateEntity,//修改用户对象
      userUpdateEntityRles,//修改用户对象校验规则
      activeDataRowIds: [],//数据表勾选的数据
    };
  },
  methods: {
    //页面初始化加载的资源数据
    initData() {
      //加载企业树数据(只加载一次)
      getCompanyTree().then(data => {
        let companyInfo = {};
        if (this.$auth.getLoginInfo().companyId === this.$auth.getLoginInfo().departmentId) {
          this.companyTree = data.result;//企业树数据
          companyInfo = data.result.find(t => t.companyId === this.$auth.getLoginInfo().companyId);
          let nodes = this.gettreeNode([companyInfo]);//根据登录的企业信息获取需要展开的树节点
          this.defaultExpandedTree = nodes;//设置默认展开的树节点
          this.userSearchForm.companyId = nodes[0];//设置默认的用户搜索表单使用那个企业进行用户搜索
          this.userAddEntity.companyId = nodes[0];//设置默认的新增按钮增加那个企业的用户
        } else {
          companyInfo = this.getCurrentNodeByDepartmentId(data.result, this.$auth.getLoginInfo().departmentId);
          this.companyTree = [companyInfo]
          let nodes = this.gettreeNode([companyInfo]);//根据登录的企业信息获取需要展开的树节点
          this.defaultExpandedTree = nodes;//设置默认展开的树节点
          this.userSearchForm.departmentId = nodes[0];//设置默认的用户搜索表单使用那个企业进行用户搜索
          this.userAddEntity.companyId = nodes[0];//设置默认的新增按钮增加那个企业的用户
        }
        //加载用户分页数据
        this.loadUserPageData(this.userSearchForm);
      }).catch(err => {
        this.$message.error(err);
      })
    },

    //企业树搜索监听回车按钮事件函数
    searchCompany() {
      let query = { companyName: this.companySearch }
      getCompanyTree(query).then(data => {
        if (this.$auth.getLoginInfo().companyId === this.$auth.getLoginInfo().departmentId) {
          this.companyTree = data.result;
          if (data.result && data.result[0]) {
            this.userSearchForm.companyId = data.result[0].companyId;
            this.userAddEntity.companyId = data.result[0].companyId;
            //加载用户分页数据
            this.loadUserPageData(this.userSearchForm);
          }
        } else {
          let companyInfo = this.getCurrentNodeByDepartmentId(data.result, this.$auth.getLoginInfo().departmentId);
          if (companyInfo) {
            this.companyTree = [companyInfo]
            this.userSearchForm.departmentId = companyInfo.companyId;
            this.userAddEntity.companyId = companyInfo.companyId;
            //加载用户分页数据
            this.loadUserPageData(this.userSearchForm);
          } else {
            this.companyTree = []
          }
        }

      }).catch(err => {
        this.$message.error(err);
      })
    },

    //加载用户分页数据
    loadUserPageData(userSearchForm) {
      let query = this.$deepCopy(userSearchForm);
      if (query.gender === 'ALL') {
        query.gender = null;
      }
      getUserPage(query).then(data => {
        this.userDataTotal = data.total;
        this.userData = data.result;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    //删除用户
    deleteUser(userIds) {
      this.$confirm('确认要执行删除操作吗?', '操作确认', {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        userDeleteApi(userIds).then(data => {
          this.$message.success("操作成功")
          //加载用户分页数据
          this.loadUserPageData(this.userSearchForm);
        }).catch(err => {
          this.$message.error(err);
        })
      }).catch(() => { })
    },

    //页面-用户查询搜索
    onSearch() {
      //加载用户分页数据
      this.loadUserPageData(this.userSearchForm);
    },
    //页面大小变更-事件
    pageSizeChange(pageSize) {
      this.userSearchForm.pageSize = pageSize;
      //加载用户分页数据
      this.loadUserPageData(this.userSearchForm);
    },
    //当前页变更-事件
    currentPageChange(currentPage) {
      this.userSearchForm.currentPage = currentPage;
      //加载用户分页数据
      this.loadUserPageData(this.userSearchForm);

    },
    //页面-新增按钮
    addBtn() {
      this.isOpenInsert = "insert";//设置对话框渲染的表单
      this.setDialogActiveTreeData(this.userAddEntity.companyId);
      this.setDialogActiveRoleData(this.userAddEntity.companyId);
      this.$refs.dialog.switchEvent();
    },
    //数据表-修改按钮
    updateBtn(entity) {
      this.isOpenInsert = "update";//设置对话框渲染的表单
      this.userUpdateEntity = this.$deepCopy(entity);//为了解决从表单传出的数据在修改页面进行变更,数据表格的数据页进行了变更而考虑使用深拷贝将数据拷贝后再进行修改
      this.setDialogActiveTreeData(entity.companyId);//设置对话框激活部门树的数据根据企业ID进行查询
      this.setDialogActiveRoleData(entity.companyId);//设置对话框激活角色的数据根据企业ID进行查询
      this.setDialogActiveDefaultActiveRoles(entity.userId);//设置对话框默认选中的角色数据
      this.$refs.dialog.switchEvent();//打开对话框
    },
    //数据表-删除按钮
    oneDeleteBtn(userId) {
      this.deleteUser([userId].join());
    },
    //数据表-选中数据的处理方法
    optionRowIds(rowIds) {
      this.activeDataRowIds = rowIds;
    },
    //页面-删除按钮
    delBtn() {
      if (this.activeDataRowIds.length > 0) {
        this.deleteUser(this.activeDataRowIds.join());
      } else {
        this.$message.warning("请选择要删除的用户!")
      }
    },
    //页面-导出按钮
    expBtn() {

    },
    //对话框执行确认
    async dialogConfirm(event) {
      let { checkResult, entity } = this.$refs[event].validate();
      if (checkResult) {
        if (event === 'userAddRef') {
          let result = await userAddApi(entity).then(data => {
            this.$message.success("操作成功")
            this.$refs[event].reset();
            //重置角色
            this.userAddEntity.roleIds = [];
            this.loadUserPageData(this.userSearchForm);
            return true;
          }).catch(err => {
            this.$message.error(err);
            return false;
          })
          return result;
        } else {
          let result = await userUpdateApi(entity).then(data => {
            this.$message.success("操作成功")
            this.loadUserPageData(this.userSearchForm);
            return true;
          }).catch(err => {
            this.$message.error(err);
            return false;
          })
          return result;
        }
      } else {
        return false;
      }
    },
    //获取菜单树的节点
    gettreeNode(tree, array = []) {
      if (tree) {
        tree.map(company => {
          array.push(company.companyId);
          if (company.child && company.child.length > 0) {
            this.gettreeNode(company.child, array);
          }
        })
      }
      return array;
    },

    //根据节点信息获取顶级节点
    getTreeTopNode(nodeInfo, currentNodeId) {
      //校验当前节点是否是顶级节点,顶级节点就是一个数组
      if (nodeInfo.parent.data instanceof Array) {
        let topNode = nodeInfo.parent.data.find(t => t.companyId === currentNodeId);
        return topNode.companyId;
      } else {
        return this.getTreeTopNode(nodeInfo.parent, nodeInfo.data.parentId)
      }
    },

    //树节点点击事件
    clickTreeNode(currentNode, nodeInfo) {

      let currentNodeId = currentNode.companyId;
      let topNodeId = this.getTreeTopNode(nodeInfo, currentNodeId);
      if (this.$auth.getLoginInfo().companyId !== this.$auth.getLoginInfo().departmentId) {
        this.userSearchForm.companyId = null;
        this.userSearchForm.departmentId = topNodeId;
        this.userAddEntity.companyId = null;
        this.userAddEntity.departmentId = topNodeId;
      } else if (currentNodeId === topNodeId) {
        this.userSearchForm.companyId = topNodeId;
        this.userSearchForm.departmentId = null;
        this.userAddEntity.companyId = topNodeId;
        this.userAddEntity.departmentId = null;
      } else {
        this.userSearchForm.companyId = topNodeId;
        this.userSearchForm.departmentId = currentNodeId;
        this.userAddEntity.companyId = topNodeId;
        this.userAddEntity.departmentId = currentNodeId;
      }
      this.loadUserPageData(this.userSearchForm);
    },

    //设置激活对话框中的部门树数据
    setDialogActiveTreeData(companyId) {
      let result = [this.companyTree.find(t => t.companyId === companyId)];
      this.removeTreeNodeNullChildFields(result)
      this.activeDialogCompanyTree = result;
    },

    //将激活对话框中的空子节点进行移除,防止组件渲染存在空子列
    removeTreeNodeNullChildFields(tree) {
      tree.map(t => {
        if (t.child && t.child.length > 0) {
          this.removeTreeNodeNullChildFields(t.child);
        } else {
          delete t.child;
        }
      })
    },

    //设置激活对话框中的角色数据
    setDialogActiveRoleData(companyId) {
      let searchQuery = { companyId: companyId, isEnable: true }
      getRoleList(searchQuery).then(data => {
        this.activeDialogCompanyRoles = data;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    //设置对话框用户默认拥有的角色
    setDialogActiveDefaultActiveRoles(userId) {
      userDetailsApi(userId).then(data => {
        let { nickName, departmentId, userName, roleIds, phone, email, expirationTime, cardCode, companyId } = data;
        this.userUpdateEntity = { userId, nickName, departmentId, userName, roleIds, phone, email, expirationTime, cardCode, companyId };
      }).catch(err => {
        this.$message.error(err);
      })
    },

    //根据部门ID从树中对应部门下的所有子树
    getCurrentNodeByDepartmentId(tree, departmentId) {
      return tree.map(t => {
        if (t.companyId === departmentId) {
          return t;
        } else if (t.child && t.child.length > 0) {
          return this.getCurrentNodeByDepartmentId(t.child, departmentId);
        } else {
          return undefined;
        }
      }).filter(item => item !== undefined).find(t => t.companyId === departmentId);
    }
  },
  mounted() {
    noSelectText('.userPageBox');
    this.initData();
  }
};
</script>

<style scoped lang="scss">
.companySearch {
  margin-bottom: 15px;
}

.leftDataBox {
  padding-right: 20px;
}

.rightDataBox {
  border-left: 2px solid gray;
  background-clip: content-box;
  border-image: linear-gradient(to bottom, rgb(144, 145, 145), rgb(175, 180, 172)) 1;
  padding-left: 20px;
}
</style>
